<?php
namespace Admin\Model;

use Think\Model;

class SpecialViewModel extends Model {

    //模板 template_id
    public $template_id;
    //专题 id
    public $id;

    /**
     * 预览平台编辑的模板
     */
    public function viewTemplate() {
        $id = $this->template_id;
        if (!$id) return false;
        $info = M('b2c_special_template')->where(array('id'=>$id))->find();
        return ['info' => $info];
    }

    /**
     * 预览门店编辑的模板
     */
    public function viewSpecial() {
        $id = $this->id;
        if (!$id) return false;

        $info = M('b2c_special_store')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_special_template b on a.tid=b.id', 'LEFT')
            ->field('a.*, b.title b_title, b.title2 b_title2, b.title3 b_title3, b.title4 b_title4, b.title5 b_title5,b.img_url b_img_url')
            ->where(array('a.id'=>$id))
            ->find();
        if ($info) {

            $info['title'] = $info['b_title'] ? $info['b_title']: $info['title'];
            $info['title2'] = $info['b_title2'] ? $info['b_title2']: $info['title2'];
            $info['title3'] = $info['b_title3'] ? $info['b_title3']: $info['title3'];
            $info['title4'] = $info['b_title4'] ? $info['b_title4']: $info['title4'];
            $info['title5'] = $info['b_title5'] ? $info['b_title5']: $info['title5'];
            $info['img_url'] = $info['b_img_url'] ? $info['b_img_url']: $info['img_url'];
        }
        $list = [];
        if ($info['typeids']) {
            $cart_ids = unserialize($info['typeids']);
            if (is_array($cart_ids) && !empty($cart_ids)) {
                foreach ($cart_ids as $key => $item) {
                    $pids_un = M('b2c_special_type_store')->where(array('type_id'=>$item))->find();
                    if (!empty($pids_un['goodids'])) {
                        $pids = unserialize($pids_un['goodids']);
                        $list[$key]['type_id'] = $pids_un['type_id'];
                        $list[$key]['type_name'] = $pids_un['type_name'];
                        $list[$key]['data'] = M('b2c_store_product a')
                            ->join(C('DB_PREFIX').'b2c_products b on a.product_id=b.product_id')
                            ->field('a.store_pid,a.goods_id, a.store, a.price,a.marketprice, b.name')
                            ->where(array('store_pid'=>array('in',$pids)))
                            ->order("FIELD (`store_pid`, ".implode(',', $pids).")")
                            ->select();
                    }
                }
            }
        }
        return ['info' => $info, 'list'=> $list];
    }
}